part of 'widgets.dart';

typedef VanGetter<T> = T Function();
typedef VanSetter<T> = void Function(T value);
typedef VanModelInstance<T> = T Function(dynamic value, [VoidCallback? dispose]);

class VanCtrl<T> extends ValueNotifier<T> {
  final VoidCallback? _dispose;

  T _value;

  @override
  T get value => _value;

  @override
  set value(T newValue) {
    if (_value == newValue) {
      return;
    }
    _value = newValue;
    notifyListeners();
  }

  VanCtrl(T value, {VoidCallback? dispose})
      : _value = value,
        _dispose = dispose,
        super(value);

  @override
  void dispose() {
    if (_dispose != null) _dispose();
    super.dispose();
  }

  create<E>({E? initValue, VanGetter? getter, VanModelInstance? instance}) {
    final E initValue0 = initValue ?? (getter != null ? getter() : value);
    dynamic controller;
    listener() {
      if (controller != null) {
        controller.value = (getter != null ? getter() : value);
      }
    }

    if (instance != null) {
      controller = instance(initValue0, _dispose);
    } else {
      controller = VanCtrl<E>(initValue0, dispose: () => removeListener(listener));
    }
    addListener(listener);
    return controller;
  }
}

class VanCheckedController extends VanCtrl<bool> {
  VanCheckedController(super.value, {super.dispose});

  bool get checked => value;

  set checked(bool checked) => value = checked;

  /// 切换选中状态，传 true 为选中，false 为取消选中，不传参为取反
  toggle([bool? checked]) {
    checked ??= !value;
    value = checked;
  }
}

class VanVisibleController extends VanCtrl<bool> {
  VanVisibleController(super.value, {super.dispose});

  bool get visible => value;

  set visible(bool visible) => value = visible;

  /// 切换显示状态，传 true 为显示，false 为取消隐藏，不传参为取反
  toggle([bool? visible]) {
    visible ??= !value;
    value = visible;
  }
}

class VanSelectedController extends VanCtrl<bool> {
  VanSelectedController(super.value);
}

typedef Ref<T> = VanCtrl<T>;

Ref<T> ref<T>(T defaultValue) {
  return VanCtrl<T>(defaultValue);
}


